package cn.cgj.listener;

import cn.cgj.flowable.service.FlowableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 程序启动时的操作
 */
@Component
public class AppListener {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private FlowableService flowableService;

    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(AppListener.class);

    /**
     * 数据库文件存储目录
     */
    private static final String filePath = System.getProperty("user.dir") + File.separator + "db";

    /**
     * 程序初始化
     */
    @PostConstruct
    public void init() {
        this.mysql();
        this.flowable();
    }

    public void flowable() {
        // spring文件扫描器
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources("classpath*:/process/*");
            if (resources.length != 0) {
                log.info("正在加载process目录下的流程文件");
                for (int i = 0; i < resources.length; i++) {
                    List<String> list = Stream.of(resources).map(path -> "process" + File.separator + path.getFilename()).collect(Collectors.toList());
                    flowableService.loadFlowFile(list);
                }
                log.info("加载完成");
            }
        } catch (IOException e) {
            log.info("加载失败【{}】", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * mysql数据库初始化
     */
    public void mysql() {
        try {
            String queryTableSql = "SELECT EXISTS("
                    + "SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = "
                    + "'" + jdbcTemplate.queryForObject("SELECT DATABASE()", String.class) + "'"
                    + " AND TABLE_NAME = 'business_info');";
            Integer exist = jdbcTemplate.queryForObject(queryTableSql, Integer.class);
            if (exist == 0) {
                log.info("缺少业务信息表正在创建");
                String createTableSql = "create table `business_info` (" +
                        "`id` INTEGER not null auto_increment primary key," +
                        "`process_id` varchar(50) default null," +
                        "`node` text default null," +
                        "`type` varchar(50) not null," +
                        "`is_delete` int(1) default 0" +
                        ");";
                jdbcTemplate.execute(createTableSql);
                log.info("业务信息表创建完毕");
            }
        } catch (Exception e) {
            log.error("数据库初始化SQL执行失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * sqlLIte数据库初始化
     */
    public void sqlLite() {
        // 检查目录是否存在,不存在则创建
        File directory = new File(filePath);
        if (!directory.exists()) {
            directory.mkdir();
        }
        try {
            // 创建并连接数据库
            String connectSql = String.format("jdbc:sqlite:%s/flowable.db", filePath);
            // 查询业务表是否存在
            String tableIsExistsSql = "select name from sqlite_master where type='table' and name='business_info'";
            Connection connection = DriverManager.getConnection(connectSql);
            Statement statement = connection.createStatement();
            ResultSet query = statement.executeQuery(tableIsExistsSql);
            if (!query.next()) {
                // 创建业务表
                String createTableSql = "create table `business_info` (" +
                        "`id` INTEGER not null primary key autoincrement," +
                        "`process_id` varchar(50) default null," +
                        "`node` varchar(50) default null," +
                        "`type` varchar(50) not null," +
                        "`is_delete` int(1) default 0" +
                        ");";
                statement.executeUpdate(createTableSql);
            }
            // 关闭资源
            query.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            log.error("数据库初始化SQL执行失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }

}
